<?php

namespace app\admin\controller\express;

use app\common\controller\Backend;
use app\common\model\TerminalExpress;
use think\Db;
use think\Exception;

/**
 * 快递员列管理
 *
 * @icon fa fa-circle-o
 */
class Userapply extends Backend
{

    protected $relationSearch = true;
    /**
     * User模型对象
     * @var \app\admin\model\express\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\express\UserApply();
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(["userauth"])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            foreach($list as $row){
                $row->getRelation('userauth')->visible(['username','id_no']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 通过
     * @param $ids
     * @return void
     * @throws \think\exception\DbException
     */
    public function agree($ids=null)
    {
        $row = $this->model->get($ids);
        if(!$row || $row["status"] != 0){
            $this->error("已经审核了");
        }
        Db::startTrans();
        try {
            $user = \app\admin\model\User::where("id",$row["user_id"])->field('id')->find();
            $res = $user->save(["express_type"=>1]);
            if(!$res){
                throw new Exception("已经是快递员身份");
            }
            //添加记录
            $res2 = \app\admin\model\express\User::create([
                "user_id"      => $user->id,
                "username"     => $row["username"],
                "mobile"       => $row["mobile"],
                "work_type"    => 1,
            ]);
            $res3 = $row->save([
                "status" => 1
            ]);
            if(!$res2 || !$res3){
                throw new Exception("操作失败了");
            }
            //上传终端
            $terminal_express = TerminalExpress::where("user_id",$user->id)->find();
            if(!$terminal_express){
                TerminalExpress::create([
                    "user_id"    => $user->id,
                    "express_id" => $res2->id,
                ]);
                $map_api = new \MapApi();
                $res5 = $map_api->create_terminal($user->id."_".$res2->id,$res2->id,"express",$row["username"]);
                if($res5["status"] != 0 || $res5["message"] != "OK"){
                    throw new Exception("添加到终端失败:".$res5["message"]);
                }
            }

            Db::commit();
            $this->success("操作成功");
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 驳回
     * @param $ids
     * @return string
     * @throws Exception
     * @throws \think\exception\DbException
     */
    public function refuse($ids=null)
    {
        $row = $this->model->get($ids);
        if($this->request->isPost()){
            if(!$row || $row["status"] != 0){
                $this->error("已经审核了");
            }
            Db::startTrans();
            try {
                $params = $this->request->param("row/a");
                $row->save([
                    "status" => 2,
                    "memo"   => $params["memo"]
                ]);
                Db::commit();
                $this->success("操作成功");
            }catch (Exception $e){
                $this->error($e->getMessage());
            }
        }

        $this->view->assign("row",$row);
        return $this->view->fetch();
    }
}
